package com.histone.lilian.magic;

import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.config.MagicModule;
import org.ssssssss.magicapi.model.FunctionInfo;
import org.ssssssss.magicapi.provider.FunctionServiceProvider;
import org.ssssssss.script.annotation.Comment;

import java.util.List;

/**
 * 代指当前登录的用户
 * @author histone
 */
@Component
public class FreeTableFunctions implements MagicModule {

    final FunctionServiceProvider functionServiceProvider;
    String[] NOT_FORMAT_TABLE_PREFIX = { "free_table", "sys_" };

    public FreeTableFunctions(FunctionServiceProvider functionServiceProvider) {
        this.functionServiceProvider = functionServiceProvider;
    }

    /**
     * 返回模块名，使用时通过import指令导入之后使用
     */
    @Override
    public String getModuleName() {
        return "freeTable";
    }

    @Comment("获取函数名")
    public String getFunctionName(@Comment("表名") String tableName, @Comment("动作") String action) {
        List<FunctionInfo> functionList = functionServiceProvider.list();
        String matchPath = tableName + '_' + action;

        for(FunctionInfo fi: functionList) {
            if (matchPath.equals(fi.getPath())){
                return matchPath;
            }
        }

        return "default_" + action;
    }

    @Comment("格式化表名")
    public String formatName(@Comment("原表名") String tableName) {
        if (StrUtil.startWithAny(tableName, NOT_FORMAT_TABLE_PREFIX)) {
            return tableName;
        }
        return "x_" + tableName;
    }


}
